package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.DataPermissionMapper;
import com.ushine.web.base.model.relation.RoleAndDataPermissionDO;
import com.ushine.web.base.model.system.DataPermissionDO;
import com.ushine.web.base.service.IDataPermissionService;
import com.ushine.web.base.service.IRoleAndDataPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yls
 * @Date: 2022/02/15 23:41
 * @Description:
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DataPermissionServiceImpl extends ServiceImpl<DataPermissionMapper, DataPermissionDO>
        implements IDataPermissionService {

    @Resource
    private IRoleAndDataPermissionService roleAndDataPermissionService;

    @Override
    public Boolean insertDataPermission(DataPermissionDO dataPermission) {
        return save(dataPermission);
    }

    @Override
    public Boolean updateDataPermission(DataPermissionDO dataPermission) {
        return updateById(dataPermission);
    }

    @Override
    public Boolean deleteDataPermissionById(Long id) {
        return removeById(id);
    }

    @Transactional(readOnly = true)
    @Override
    public List<DataPermissionDO> listAllDataPermissions() {
        return Optional.ofNullable(list()).orElse(new ArrayList<>(0));
    }

    @Override
    public List<DataPermissionDO> listDataPermissionsByRoleIds(Set<Long> roleIds) {
        LambdaQueryWrapper<RoleAndDataPermissionDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(RoleAndDataPermissionDO::getRoleId, roleIds)
                .select(RoleAndDataPermissionDO::getDataPermissionId);
        // 获取角色和数据权限
        List<RoleAndDataPermissionDO> roleAndDataPermissions = roleAndDataPermissionService.list(lambdaQueryWrapper);
        roleAndDataPermissions = Optional.ofNullable(roleAndDataPermissions).orElse(new ArrayList<>(0));
        Set<Long> dataPermissionIds = roleAndDataPermissions.stream()
                .map(RoleAndDataPermissionDO::getDataPermissionId).collect(Collectors.toSet());
        List<DataPermissionDO> dataPermissionList = listByIds(dataPermissionIds);
        return Optional.ofNullable(dataPermissionList).orElse(new ArrayList<>(0));
    }
}
